import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder} from '@angular/forms';
import {ProgrammeGridComponent} from '../../components/programme-grid/programme-grid.component';
import {ProgrammeFilterComponent} from '../../components/programme-filter/programme-filter.component';
import {ProgrammeFormComponent} from '../../components/programme-form/programme-form.component';
import {ProgrammeService} from '../../services/programme.service';

@Component({
  selector: 'app-programme-index',
  templateUrl: './programme-index.component.html',
  styles: []
})

export class ProgrammeIndexComponent implements OnInit {

  @ViewChild('programmeFilter') programmeFilter: ProgrammeFilterComponent;
  @ViewChild('programmeGrid') programmeGrid: ProgrammeGridComponent;
  @ViewChild('programmeForm') programmeForm: ProgrammeFormComponent;
  currentStep: string;

  currentSelection: any;

  constructor(private fb: FormBuilder, private programmeService: ProgrammeService) {

  }

  ngOnInit() {
    this.currentStep = 'list';
  }

  ngAfterViewInit() {
    this.onSearch();
  }

  onSearch(): void {
    this.programmeGrid.setParams(this.programmeFilter.getParams());
    this.programmeGrid.flushData();
  }

  onEdit(entity) {
    this.currentStep = 'form';
    this.currentSelection = entity;
  }

  onAdd() {
    this.currentStep = 'form';
    this.currentSelection = {};
  }

  onRemove(entity) {
    this.currentStep = 'form';
    this.currentSelection = entity;
  }

  onProject(entity): void {

  }

  onEditSelect() {
    const selections = this.programmeGrid.getSelections();
    if (selections.length === 1) {
      this.onEdit(selections[0]);
    }
  }

  async onRemoveSelections() {
    const selections = this.programmeGrid.getSelections();
    const ids = [];
    selections.forEach(function (item) {
      ids.push(item.id);
    });
    await this.programmeService.deleteProgrammes(ids);
    this.programmeGrid.flushData();
  }

  async onOk(entity) {
    this.currentStep = 'list';
    Object.assign(this.currentSelection, entity);
    let result;
    if (this.currentSelection.id) {
      result = await this.programmeService.updateProgramme(this.currentSelection);
    } else {
      result = await this.programmeService.saveProgramme(this.currentSelection);
    }
    this.programmeGrid.flushData();
  }

  onCancel(entity) {
    this.currentStep = 'list';
  }
}
